package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IUserLoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.User;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author hanshuai
 * @version 1.0
 * @description 完成登录模块
 * @date 2021/12/12 13:54
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements IUserLoginService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;
    @Autowired
    IKaptchaService iKaptchaService;

    @Override
    public UserLoginResponse userLogin(String username, String password) {

        UserLoginResponse response = new UserLoginResponse();
        Example example = new Example(Member.class);
        //密码加密
        String mdPassowrd = DigestUtils.md5DigestAsHex(password.getBytes());
        //查询密码和用户名是否匹配
        example.createCriteria().andEqualTo("username", username).andEqualTo("password", mdPassowrd);
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)) {
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getMessage());
            return response;
        }
        //走到这里说明用户名和密码没有问题
        // 判断members的数量，不等于1则说明数据有问题
        if (members.size() != 1) {
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
            return response;
        }
        // 如果没有激活也不让登录
        if ("N".equals(members.get(0).getIsVerified())) {
            response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getMessage());
            return response;
        }
        //都没有问题就可以让用户登录了
        //此时需要给用户token
        Map<String, Object> tokens = new HashMap<>();
        tokens.put("uid", members.get(0).getId());
        tokens.put("file", members.get(0).getFile());
        tokens.put("username", members.get(0).getUsername());
        JwtTokenUtils build = JwtTokenUtils.builder().msg(JSON.toJSONString(tokens)).build();


        String token = build.creatJwtToken();
        members.get(0).setUpdated(new Date());
        UserLoginResponse successResponse = userConverterMapper.converter(members.get(0));
        successResponse.setToken(token);
        successResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        successResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return successResponse;
    }

    @Override
    public UserLoginGetResponse userLoginGet(String token) {
        UserLoginGetResponse response = new UserLoginGetResponse();
        JwtTokenUtils build = JwtTokenUtils.builder().token(token).build();
        //获得解密后的token
        String decode = build.freeJwt();
        String substring = decode.substring(1, decode.length() - 1);
        String replace = substring.replace("\"", "");
        //将解密后的token转化为map
        Map map = string2Map(replace);
        Set set = map.keySet();
        for (Object o : set) {
            System.out.println(o);
        }
        Integer uid =Integer.parseInt((String) map.get("uid"));
        String username = (String) map.get("username");

        //判断一下是否有错误
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("id", uid).andEqualTo("username", username);
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() != 1) {
            response.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return response;
        }

        //用converter转换一下
        UserLoginGetResponse successResponse = userConverterMapper.converterGet(members.get(0));
        successResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        successResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return successResponse;
    }

    /**
     * 解析token
     *
     * @param checkAuthRequest
     * @return
     */
    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {
        String token = checkAuthRequest.getToken();
        CheckAuthResponse response = new CheckAuthResponse();
        JwtTokenUtils build = JwtTokenUtils.builder().token(token).build();
        //获得解密后的token
        String decode = build.freeJwt();
        if (!decode.contains("uid")) {
            response.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return response;
        }

        response.setUserInfo(decode);
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    private Map string2Map(String decode) {
        Map<String, Object> map = new HashMap<>();
        String[] split = decode.split(",");
        for (String unit : split) {
            String[] littleUnit = unit.split(":");
            map.put(littleUnit[0], littleUnit[1]);
        }
        return map;
    }
}
